package com.codeest.geeknews.ui.main.fragment;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.LightingColorFilter;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.DimenRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.Space;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.codeest.geeknews.R;
import com.codeest.geeknews.model.bean.DoubanChannelBean.GroupsBean.ChlsBean;
import com.codeest.geeknews.ui.main.adapter.DoubanChannelAdapter;
import com.codeest.geeknews.util.StatusBarUtil;
import com.codeest.geeknews.widget.FitStatusBarBottomSheetDialog;
import com.trycatch.mysnackbar.Prompt;
import com.trycatch.mysnackbar.TSnackbar;

import java.util.List;

public class DoubanChannelFragment extends BottomSheetDialogFragment {

    public static final String TAG = "DoubanChannelFragment";
    private DoubanChannelAdapter mAdapter;
    private Builder builder;

    private View contentView;
    private RecyclerView rc_gallery;
    private float snackBarHeight;
    private TSnackbar snackBar;
    private boolean isShow;


    private BottomSheetBehavior.BottomSheetCallback mBottomSheetBehaviorCallback = new BottomSheetBehavior.BottomSheetCallback() {
        //这里是bottomSheet状态的改变
        @Override
        public void onStateChanged(@NonNull View bottomSheet, int newState) {
            if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                dismiss();
                //getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            }
            //BottomSheetBehavior.STATE_DRAGGING;
            //BottomSheetBehavior.STATE_SETTLING;
            //BottomSheetBehavior.STATE_EXPANDED;
            //BottomSheetBehavior.STATE_COLLAPSED;
            //BottomSheetBehavior.STATE_HIDDEN;
        }

        private float preSlideOffset;

        //这里是拖拽中的回调，根据slideOffset可以做一些动画
        @Override
        public void onSlide(@NonNull View bottomSheet, float slideOffset) {
            //Log.e(TAG, "slideOffset =" + slideOffset + "");
            showHideSnackbar(slideOffset, preSlideOffset);
            preSlideOffset = slideOffset;
        }
    };

    @Override
    public void onViewCreated(View contentView, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(contentView, savedInstanceState);
    }

    private void showHideSnackbar(float slideOffset, float preSlideOffset) {
        //if (slideOffset == 1.0f && !isShow) {//TSnackbar动画显示有点慢
        if (slideOffset >= 0.8f && !isShow) {
            setupSnackbar();
            snackBar.show();
            isShow = true;
            //} else if ((preSlideOffset > slideOffset) && isShow) {//往下滑
        } else if (slideOffset < 0.8f && (preSlideOffset > slideOffset) && isShow) {//往下滑
            snackBar.dismiss();
            snackBar = null;
            isShow = false;
        }
    }

    private void setupSnackbar() {
        final ViewGroup viewGroup = (ViewGroup) contentView.findViewById(R.id.content).getRootView();
        //final ViewGroup viewGroup = (ViewGroup) contentView.getParent();
        View view = LayoutInflater.from(getContext()).inflate(R.layout.view_toolbar, null);
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        setToolBar(toolbar, "频道");
        snackBar = TSnackbar.make(viewGroup, "", TSnackbar.LENGTH_INDEFINITE, TSnackbar.APPEAR_FROM_TOP_TO_DOWN);
        ((TSnackbar.SnackbarFramelayout) snackBar.getView()).removeAllViews();
        ((TSnackbar.SnackbarFramelayout) snackBar.getView()).addView(view);
        snackBar.setPromptThemBackground(Prompt.SUCCESS);
    }

    protected void setToolBar(Toolbar toolbar, String title) {
        toolbar.setBackgroundResource(Prompt.SUCCESS.getBackgroundColor());
        TextView titleView = ((TextView) toolbar.findViewById(R.id.title));
        if (titleView != null) {
            titleView.setText(title);
            toolbar.setTitle("");
        } else {
            toolbar.setTitle(title);
        }
        Drawable navigationIconDrawable = getResources().getDrawable(R.drawable.ic_action_navigation_arrow_back);//颜色灰色
        navigationIconDrawable.setColorFilter(new LightingColorFilter(Color.GRAY, 0xFFFFFF));//设置滤镜，使成为白色箭头
        toolbar.setNavigationIcon(navigationIconDrawable);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
    }

    protected void fetToatalHeightOfSnackbarAndToolbar() {
        //
        TypedValue tv = new TypedValue();
        int actionBarHeight = 0;
        if (getActivity().getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getActivity().getResources().getDisplayMetrics());
        }
        snackBarHeight = StatusBarUtil.getStatusBarHeight(getActivity()) + actionBarHeight;
        //
    }

    public void show(FragmentManager fragmentManager) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.add(this, getTag());
        ft.commitAllowingStateLoss();
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        //return new FitStatusBarBottomSheetDialog(getContext(), getTheme());
        return new FitStatusBarBottomSheetDialog(getContext(), R.style.BottomSheetDialogStyle);//自定义样式
    }

//    @Override
//    public void setStyle(int style, @StyleRes int theme) {
//        super.setStyle(style, R.style.BottomSheetDialog);
//    }

    @Override
    public void setupDialog(Dialog dialog, int style) {
        super.setupDialog(dialog, style);
        contentView = View.inflate(getContext(), R.layout.dialog_music_channel, null);
        dialog.setContentView(contentView);
        ((FrameLayout) contentView.getParent()).setBackgroundColor(getResources().getColor(android.R.color.transparent));
        CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) ((View) contentView.getParent()).getLayoutParams();
        CoordinatorLayout.Behavior behavior = layoutParams.getBehavior();
        if (behavior != null && behavior instanceof BottomSheetBehavior) {
            if (builder.peekHeight > 0) {
                ((BottomSheetBehavior) behavior).setPeekHeight((int) (builder.peekHeight + snackBarHeight));// 设置当关闭时 底部 的高度 app:behavior_peekHeight="50dp"
            }
            ((BottomSheetBehavior) behavior).setSkipCollapsed(true);
            ((BottomSheetBehavior) behavior).setHideable(true);//设置当拉升到底部是否可以隐藏  app:behavior_hideable="true"
            ((BottomSheetBehavior) behavior).setBottomSheetCallback(mBottomSheetBehaviorCallback);
        }
        rc_gallery = (RecyclerView) contentView.findViewById(R.id.rv_content);
        Space space = (Space) contentView.findViewById(R.id.space);
        fetToatalHeightOfSnackbarAndToolbar();
        setRecyclerView();
        setSpaceHeight(space);
        //拦截返回键
        /*getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && (snackBar != null && snackBar.isShown())) {
                    //
                    return true;
                }
                return false;
            }
        });*/
    }

    private void setSpaceHeight(Space space) {
        space.setBackgroundColor(getResources().getColor(android.R.color.transparent));
        space.getLayoutParams().height = (int) snackBarHeight;
    }

    private void setRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        rc_gallery.setLayoutManager(layoutManager);
        mAdapter = new DoubanChannelAdapter(builder.data);
        rc_gallery.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new DoubanChannelAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                builder.onItemSelectedListener.onItemSelected(view, position);
                dismiss();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    public static class Builder {
        private Context context;
        private int spacing = 1;
        private int peekHeight = -1;
        private List<ChlsBean> data;
        private OnItemSelectedListener onItemSelectedListener;

        public Builder(@NonNull Context context) {
            this.context = context;
        }


        public Builder setSpacing(int spacing) {
            this.spacing = spacing;
            return this;
        }

        public Builder setSpacingResId(@DimenRes int dimenResId) {
            this.spacing = context.getResources().getDimensionPixelSize(dimenResId);
            return this;
        }

        public Builder setPeekHeight(int peekHeight) {
            this.peekHeight = peekHeight;
            return this;
        }

        public Builder setPeekHeightResId(@DimenRes int dimenResId) {
            this.peekHeight = context.getResources().getDimensionPixelSize(dimenResId);
            return this;
        }

        public DoubanChannelFragment create() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
                    && ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                throw new RuntimeException("Missing required WRITE_EXTERNAL_STORAGE permission. Did you remember to request it first?");
            }
            DoubanChannelFragment customBottomSheetDialogFragment = new DoubanChannelFragment();
            customBottomSheetDialogFragment.builder = this;
            return customBottomSheetDialogFragment;
        }

        public Builder setData(List<ChlsBean> data) {
            this.data = data;
            return this;
        }

        public OnItemSelectedListener getOnItemSelectedListener() {
            return onItemSelectedListener;
        }

        public Builder setOnItemSelectedListener(OnItemSelectedListener onItemSelectedListener) {
            this.onItemSelectedListener = onItemSelectedListener;
            return this;
        }
    }

    public interface OnItemSelectedListener {
        void onItemSelected(View view, int position);

    }
}
